package com.bt.framework.ext

import android.graphics.Rect
import android.graphics.drawable.GradientDrawable
import android.view.View
import android.view.ViewConfiguration
import androidx.core.graphics.toColorInt
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.bt.framework.decoration.SumDividerItemDecoration
import com.bt.framework.utils.dpToPx
import kotlin.math.abs

/**
 *@author:hxm
 *@date: 2025/6/17 22:52
 *@version:
 *@description:
 */

private var isLock = true

/**
 * 监听RecyclerView滑动
 * @param onScrolledUp 滑动到顶部
 * @param onScrolledDown 滑动到底部
 * @param onScrolledToTop 滚动到顶部
 * @param onScrolledToBottom 滚动到底部
 * @param once 是否只执行一次
 */
fun RecyclerView.addOnVerticalScrollListener(
    onScrolledUp: (recyclerView: RecyclerView) -> Unit,
    onScrolledDown: (recyclerView: RecyclerView) -> Unit,
    onScrolledToTop: (recyclerView: RecyclerView) -> Unit,
    onScrolledToBottom: (recyclerView: RecyclerView) -> Unit,
    once: Boolean = true
) {
    addOnScrollListener(object : RecyclerView.OnScrollListener() {
        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            if (!recyclerView.canScrollVertically(-1)) {
                //顶部
                onScrolledUp.invoke(recyclerView)
            } else if (!recyclerView.canScrollVertically(1)) {
                //底部
                onScrolledDown.invoke(recyclerView)
            } else if (dy < 0 && abs(dy) > ViewConfiguration.get(context).scaledTouchSlop) {
                //上滑
                if (once && !isLock) {
                    isLock = true
                    onScrolledToTop.invoke(recyclerView)
                } else if (!once) {
                    onScrolledToTop.invoke(recyclerView)
                }
            } else if (dy > 0 && abs(dy) > ViewConfiguration.get(context).scaledTouchSlop) {
                //下滑
                if (once && isLock) {
                    isLock = false
                    onScrolledToBottom.invoke(recyclerView)
                } else if (!once) {
                    onScrolledToBottom.invoke(recyclerView)
                }
            }
        }
    })
}

/**
 * 设置分割线
 * @param color 分割线的颜色，默认是#DEDEDE
 * @param size 分割线的大小，默认是1px
 * @param includeLast 最后一条是否绘制
 *
 */
fun RecyclerView.divider(
    color: Int = "#DEDEDE".toColorInt(),
    size: Int = 1,
    includeLast: Boolean = true
): RecyclerView {
    addItemDecoration(SumDividerItemDecoration(context, orientation).apply {
        setDrawable(GradientDrawable().apply {
            setColor(color)
            shape = GradientDrawable.RECTANGLE
            setSize(size, size)
            isDrawLastPositionDivider(includeLast)
            if (itemDecorationCount > 0) {
                removeItemDecorationAt(0)
            }
        })
    })
    return this
}

/**
 * 设置网格分割线间隔
 * @param spanCount 网格的列数
 * @param spacingDp 分割线的大小
 * @param includeEdge 是否包含边缘
 *
 */
fun RecyclerView.dividerGridSpace(
    spanCount: Int,
    spacingDp: Float,
    includeEdge: Boolean
): RecyclerView {
    addItemDecoration(object : RecyclerView.ItemDecoration() {
        override fun getItemOffsets(
            outRect: Rect,
            view: View,
            parent: RecyclerView,
            state: RecyclerView.State
        ) {
            val position = parent.getChildAdapterPosition(view)
            val column = position % spanCount
            val targetSpacing = dpToPx(spacingDp).toInt()
            if (includeEdge) {
                outRect.left = targetSpacing - column * targetSpacing / spanCount
                outRect.right = (column + 1) * targetSpacing / spanCount
                if (position < spanCount) {
                    outRect.top = targetSpacing
                }
                outRect.bottom = targetSpacing
            } else {
                outRect.left = column * targetSpacing / spanCount
                outRect.right = targetSpacing - (column + 1) * targetSpacing / spanCount
                if (position >= spanCount) {
                    outRect.top = targetSpacing
                }
            }
        }
    })
    return this
}

/**
 * 获取RecyclerView的布局方向
 */
fun RecyclerView.vertical(spanCount: Int = 0, isStaggered: Boolean = false): RecyclerView {
    layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
    if (spanCount != 0) {
        layoutManager = GridLayoutManager(context, spanCount, GridLayoutManager.VERTICAL, false)
    }
    if (isStaggered) {
        layoutManager = StaggeredGridLayoutManager(spanCount, StaggeredGridLayoutManager.VERTICAL)
    }
    return this
}

/**
 * 设置RecyclerView的item动画
 */
fun RecyclerView.itemAnimator(animator: RecyclerView.ItemAnimator): RecyclerView {
    itemAnimator = animator
    return this
}

/**
 * 禁用RecyclerView的item动画
 */
fun RecyclerView.noItemAnim() {
    itemAnimator = null
}

/**
 * 设置RecyclerView为水平布局
 */
fun RecyclerView.horizontal(spanCount: Int = 0, isStaggered: Boolean = false): RecyclerView {
    layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
    if (spanCount != 0) {
        layoutManager = GridLayoutManager(context, spanCount, GridLayoutManager.HORIZONTAL, false)
    }
    if (isStaggered) {
        layoutManager = StaggeredGridLayoutManager(spanCount, StaggeredGridLayoutManager.HORIZONTAL)
    }
    return this
}


/**
 * 获取RecyclerView的布局方向
 */
inline val RecyclerView.orientation
    get() = if (layoutManager == null) -1 else layoutManager.run {
        when (this) {
            is LinearLayoutManager -> orientation
            is GridLayoutManager -> orientation
            is StaggeredGridLayoutManager -> orientation
            else -> -1
        }
    }